# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.views.generic.list_detail import object_list, object_detail
from django.views.generic.create_update import create_object, delete_object, \
    update_object
from django.template import Context, loader
from django.http import HttpResponse, Http404, HttpResponseBadRequest

from django.shortcuts import render_to_response
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.template import RequestContext
from datetime import datetime
#use built in auth model
from django.contrib.auth.models import User

import sys
import logging

from metaweb import process_write_multi, process_write_compound, \
    process_write_mixed
from write_logic import process_create, process_write_blurb
from write_logic import process_link_type

from metaweb import get_domain_used, get_bioventurist_domain

from utils import *
from bvapp.models import Emails
from ragendja.dbutils import *
from freebase import sandbox
########################################################################
# NEW PART OF READ-WRITE CODE
#
from utils import *
from ragendja import template

def company(request, id):
    company = CompanyReader(SandboxRetriever(), '/'+id)
    return template.render_to_response(request,
       'bvapp/company.html',
       {'c': company})


def echo(request):
    data = request.POST.get("value", None)
    if data:
        return HttpResponse("%s [modified %s] " % (data, datetime.now()))
    return HttpResponse("No data")

def selects(request, type=None):

    def ticker_symbols(request):
        query = [{
            "type": "/finance/stock_exchange",
            "id": None,
            "name": None,
            "limit": 1000
        }]
        response = HttpResponse(
            simplejson.dumps(sandbox.mqlread(query)),
            mimetype="application/json")
        return response
    
    def areas_of_expertise(request):
        query = [{
            "type": "/base/bioventurist/technology_class",
            "id": None,
            "name": None,
            "limit": 1000
        }]
        response = HttpResponse(
            simplejson.dumps(sandbox.mqlread(query)),
            mimetype="application/json")
        return response

    functions = {
        "ticker_symbols": ticker_symbols,
        "areas_of_expertise": areas_of_expertise
    }
    if not type or not functions.has_key(type):
        raise ValueError("You should specify a correct type, e.g. areas_of_expertise, ticker_symbols, etc...")
    return functions[type](request)


    
def company_write(request, type):

    id = request.POST.get("company_id", "")    
    company = CompanyWriter(SandboxRetriever(), "/"+id)
    
    TYPE_FUNCTIONS = {
        "overview": company.overview,
        "ticker_symbol": company.ticker_symbol,
        "area_of_expertise": company.area_of_expertise,
        
    }

    try:
        writer_reponse = TYPE_FUNCTIONS[type](request)
    except KeyError:
        return HttpResponseBadRequest("Unsupported property of Company object")
    else:
        return HttpResponse(writer_reponse)


########################################################################
# TOPIC PAGES:

def generate_topic_page(request, topic_id, html_page):
    '''
    General renderer of topic pages
    @var topic_name: name of the topic;
    @var html_page: the html template;
    '''
    return render_to_response('topic_pages/'+html_page,
        {'topic_id': topic_id,
        'domain_used' : get_domain_used(),
        'bioventurist_domain' : get_bioventurist_domain()},
        context_instance=RequestContext(request) )

def company_old_page(request, topic_id):
    '''
    Render a company topic page;
    @var topic_name: name of the topic
    '''
    return generate_topic_page(request, topic_id, 'company.html')

def disease_page(request,diseaseName):
    '''Render a disease topic page;
            request = the HttpRequest;
            topic_name = name of the topic;
        Returns the HttpResponse.'''
    return generate_topic_page(request, diseaseName, 'disease.html')

def technology_page(request,technologyName):
    '''Render a technology topic page;
            request = the HttpRequest;
            topic_name = name of the topic;
        Returns the HttpResponse.'''
    return generate_topic_page(request, technologyName, 'technology.html')

def product_page(request,productName):
    '''Render a product topic page;
            request = the HttpRequest;
            topic_name = name of the topic;
        Returns the HttpResponse.'''
    return generate_topic_page(request, productName, 'product.html')

def biomolecule_page(request,biomoleculeName):
    '''Render a biomolecule topic page;
            request = the HttpRequest;
            topic_name = name of the topic;
        Returns the HttpResponse.'''
    return generate_topic_page(request, biomoleculeName, 'biomolecule.html')

def therapeutic_page(request,therapeuticName):
    '''Render a therapeutic topic page;
            request = the HttpRequest;
            topic_name = name of the topic;
        Returns the HttpResponse.'''
    return generate_topic_page(request, therapeuticName, 'therapeutic.html')

def vcfirm_page(request,vcfirmName):
    '''Render a VC Firm topic page;
            request = the HttpRequest;
            topic_name = name of the topic;
        Returns the HttpResponse.'''
    return generate_topic_page(request, vcfirmName, 'vcfirm.html')

def researchgroup_page(request,researchgroupName):
    '''Render a research group topic page;
            request = the HttpRequest;
            topic_name = name of the topic;
        Returns the HttpResponse.'''
    return generate_topic_page(request, researchgroupName, 'researchgroup.html')


#################################################################
# LIST PAGES
def list_page(request, html_page):
    '''General renderer of list pages;
            request = the HttpRequest;
            html_page = the html template;
        Returns the HttpResponse.'''
    return render_to_response('list_pages/'+html_page, {'domain_used' : get_domain_used(), 'bioventurist_domain' : get_bioventurist_domain()}, context_instance=RequestContext(request) )

def companies_page(request):
    '''Renderer of company list pages;
            request = the HttpRequest;
        Returns the HttpResponse.'''
    return list_page(request, 'companies.html')

def diseases_page(request):
    '''Renderer of disease list pages;
            request = the HttpRequest;
        Returns the HttpResponse.'''
    return list_page(request, 'diseases.html')

def technologies_page(request):
    '''Renderer of technology list pages;
            request = the HttpRequest;
        Returns the HttpResponse.'''
    return list_page(request, 'technologies.html')

def products_page(request):
    '''Renderer of product list pages;
        request = the HttpRequest;
    Returns the HttpResponse.'''
    return list_page(request, 'products.html')

def vcfirms_page(request):
    '''Renderer of vcFirm list pages;
        request = the HttpRequest;
    Returns the HttpResponse.'''
    return list_page(request, 'vcfirms.html')

def researchgroups_page(request):
    '''Renderer of recearch group list pages;
            request = the HttpRequest;
        Returns the HttpResponse.'''
    return list_page(request, 'researchgroups.html')


##################################################################
# ANALYSIS PAGES - TODO: Put in a different app.
def analysis_page(request):
    return render_to_response('analysis.html',{'domain_used' : get_domain_used()}, context_instance=RequestContext(request) )

def vcfinancings_page(request):
    return render_to_response('vcfinancings.html',{'domain_used' : get_domain_used(), 'bioventurist_domain' : get_bioventurist_domain()}, context_instance=RequestContext(request) )


def rssfeeds_page(request):
    return render_to_response('rss_feeds.html',{'domain_used' : get_domain_used()}, context_instance=RequestContext(request) )

def test_page(request):
    return render_to_response('test.html',{'domain_used' : get_domain_used()}, context_instance=RequestContext(request) )




#def company_info_edit_page(request,companyName):
#   return render_to_response('company_info_edit.html',{'company_name': companyName, 'domain_used' : get_domain_used()}, context_instance=RequestContext(request) )

def company_info_write_page(request, companyName):
    logging.debug('----------comapny_info_write---------- '+companyName + ' , ' + request.method);
    if request.method == 'GET':
        logging.error('GET not supported for company info writing');
        html = "<html><body>Sorry, GET not supported</body></html>"
    elif request.method == 'POST':
        logging.debug('command: POST   ');
        html = process_write(request, companyName)
    return HttpResponse(html)

def topic_info_write_multi_page(request, topic_id):
    logging.debug('----------topic_info_write_multi_page---------- '+topic_id + ' , ' + request.method);
    if request.method == 'GET':
        logging.error('GET not supported for writing');
        html = "<html><body>Sorry, GET not supported</body></html>"
    elif request.method == 'POST':
        logging.debug('command: POST   ');
        logging.debug('testing');
        html = process_write_multi(request)
    return HttpResponse(html)

def topic_info_write_mixed_page(request, topic_id):
    logging.debug('----------topic_info_write_mixed_page---------- '+topic_id + ' , ' + request.method);
    if request.method == 'GET':
        logging.error('GET not supported for writing');
        html = "<html><body>Sorry, GET not supported</body></html>"
    elif request.method == 'POST':
        logging.debug('command: POST   ');
        logging.debug('testing');
        html = process_write_mixed(request)
    return HttpResponse(html)


def topic_info_write_compound_page(request, topic_id):
    logging.debug('----------topic_info_write_compound---------- '+topic_id + ' , ' + request.method+'\n');
    html = process_write_compound(request, topic_id)
    return HttpResponse(html)


def topic_info_write_blurb(request, topic_id):
    logging.debug('----------topic_info_write_blurb---------- '+topic_id + ' , ' + request.method);
    if request.method == 'GET':
        logging.error(' '+ 'GET');
        html = "<html><body>Sorry, GET not supported</body></html>"
        return HttpResponse(html)
    elif request.method == 'POST':
        logging.debug('command: POST   ');
        html = process_write_blurb(request, topic_id)
        return HttpResponse(html)


def create_topic_page(request, topicName):
    logging.debug('----------create_topic---------- '+topicName + ' , ' + request.method + '/n');
    if request.method == 'GET':
        logging.error(' '+ 'GET');
        html = "<html><body>Sorry, GET not supported </body></html>"
        return HttpResponse(html)
    elif request.method == 'POST':
        logging.debug('command: POST   ');
        html = process_create(request, topicName)
        return HttpResponse(html)

def link_type_page(request):
    logging.debug('----------link_type---------- ');
    if request.method == 'GET':
        logging.error(' '+ 'GET');
        html = "<html><body>Sorry, GET not supported</body></html>"
        return HttpResponse(html)
    elif request.method == 'POST':
        logging.debug('command: POST   ');
        html = process_link_type(request)
        return HttpResponse(html)


def add_email_page(request):


##    greetings = get_object_list(Emails)
##    html = ''
##    for greeting in greetings:
##        html +='<b>%s</b> wrote:' % greeting.subscribedemail
##
##    return HttpResponse(html)

    if request.method == 'POST':
        logging.debug('command: POST   ');
        posts = request._get_post()
        email = Emails()
        email.subscribedemail = posts['emailval']
        email.put()


    return render_to_response('main.html', {'domain_used' : get_domain_used(), 'bioventurist_domain' : get_bioventurist_domain(), 'emailadded' : posts['emailval']}, context_instance=RequestContext(request) )

def render_xml(request):
    c = Context()
    response = HttpResponse(mimetype="text/xml")
    t = loader.get_template("xml/sitemap.xml")
    response.write(t.render(c))
    return response

#def test_login(request):
#    return render_to_response('testlogin.html',{'domain_used' : get_domain_used()})

#def rpx_response(request):
    #print('rpxtoken handler called')
    #sys.stderr.write('rpxtoken handler called')
#    rpx_response = RPXTokenHandler(request)
#    user_login(rpx_response)
#    sys.stderr.write(rpx_response+'\n')

#    return render_to_response('logged_in.html',{'rpx' : rpx_response})
